/**
 * Created by xinxinran on 2017/1/3.
 */
'use strict';

const winston = require('winston');
let loggerConfig;
const loggers = {},
    defaultLoggerName = '_default',
    cUtil = require('./commonUtil');

function backupLoggerOperation(lv, args){
    const txt = args && args.shift();
    console.log('*[temp log] [%s] : %s, %s', lv, txt, args);
}

function makeLogger(loggerName, conf){
    let transports, logger = null, lConfig = conf || loggerConfig;
    if(!lConfig){
        if(logger = loggers['__tempLogger']){
            return logger;
        }

        logger = {
            debug : function(){
                backupLoggerOperation('debug', Array.prototype.slice.call(arguments));
            },
            info : function(){
                backupLoggerOperation('info', Array.prototype.slice.call(arguments));
            },
            warn : function(){
                backupLoggerOperation('warn', Array.prototype.slice.call(arguments));
            },
            error : function(){
                backupLoggerOperation('error', Array.prototype.slice.call(arguments));
            }
        };

        loggers['__tempLogger'] = logger;

        return logger;

    }

    transports = [];

    cUtil.each(lConfig, function(name, conf){
        try {
            transports.push(new (winston.transports[name])(conf));
        }catch(e){
            console.warn('Fail to create transport for winston, caused by : %s', e);
        }
    });

    if(transports.length){
        logger = new (winston.Logger)({
            transports : transports
        });
    }

    loggers[loggerName] = logger;

    return logger;
}

module.exports = {
    initLogger : function(conf){
        loggerConfig = conf;
    },
    getLogger : function(loggerName, conf){
        const lName = loggerName || defaultLoggerName;
        let nowLogger = loggers[lName];
        nowLogger = nowLogger || makeLogger(lName, conf);
        return nowLogger;
    }
};